<template>
  <div class="p-5 pt-6" style="background-color: #f9f9f9;  min-height: 100Vh;">
    <div class="mb-5">
      <h1 style="color: #3b8cff" @click="switchDate"><van-icon size="20" color="#3b8cff" name="notes-o" />
        {{selectDateLabel}} <van-icon color="#3b8cff" name="arrow-down" /></h1>

      <van-popup v-model:show="showDatePopup" :close-on-click-overlay="false"  position="bottom" :style="{ 'min-height': '30%' }">
        <div style="padding:30px 10px">
          <CustomDate ref="customDateRef" :selectDateType="selectDateType" @updateParentSelectDataType="updateParentSelectDataType"/>
          <div style="padding-top: 20px">
            <van-row :gutter="[10]">
              <van-col span="12">
                <van-button type="default" style="width:100%" block @click="cancelDate">清空</van-button>
              </van-col>
              <van-col span="12">
                <van-button type="primary" :disabled="selectDateType === null" style="width:100%" block @click="confirmDate">确认</van-button>
              </van-col>
            </van-row>
          </div>
        </div>
      </van-popup>

    </div>
    <div class="pb-6">
      <div class="flex flex-col">
        <h4 class="mb-2">潜客数据</h4>
        <van-row :gutter="[20, 20]">
          <van-col span="8" v-for="(item,key) in dataInfo" :key="key">
            <div class="flex flex-col">
              <span style="color: #888888;font-size: 14px">{{item.name}} <van-icon @click="showInfo(item)" name="info-o" /></span>
              <span style="color: #888888">{{item.num}}</span>
            </div>
          </van-col>
        </van-row>
      </div>
      <van-popup v-model:show="showInfoPopup" position="bottom" close-icon-position="top-left" :style="{ 'min-height': '20%' }">
        <div class="p-5">
          <h1 class="text-center pb-2">{{selectInfo?.name}}</h1>
          <span class="infoDetail">{{selectInfo?.info}}</span>
        </div>
      </van-popup>
    </div>





    <div class="pb-6 pt-2">
      <div class="flex justify-between items-center ">
        <h4 class="mb-2">潜客阶段</h4>
        <div class="flex">
          <div class="border p-1 pl-4 pr-4"
               :style="{ backgroundColor: phaseChartType === 'bar' ? '#eef2fe' : '#ffffff' }"
                @click="switchStatusChartType('bar')">
            <van-icon size="20" :style="{ color: phaseChartType === 'bar' ? '#4f75f0' : '#000000' }" name="bar-chart-o" />
          </div>
          <div class="border p-1 pl-4 pr-4"
               :style="{ backgroundColor: phaseChartType === 'funnel' ? '#eef2fe' : '#ffffff' }"
               @click="switchStatusChartType('funnel')">
            <van-icon size="20" :style="{ color: phaseChartType === 'funnel' ? '#4f75f0' : '#000000' }" name="points" />
          </div>
        </div>
      </div>
      <div class="pt-2" ref="phaseChart" style="width: 100%; min-height: 400px;"></div>
    </div>

    <div class="pb-20">
      <div class="flex">
        <h4 class="mb-2 mr-2">潜客状态 <van-icon color="#888888" size="18" name="info-o" /></h4>
      </div>
      <div class="pt-2" ref="statusChart" style="width: 100%; min-height: 600px;"></div>
    </div>

    <Nav></Nav>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {
  format,
  startOfMonth,
  endOfMonth
} from "date-fns";
import {CustomDate, Nav} from '@/views/components/leads';
import {LeadsAnalysisChart, LeadsAnalysisDataType, LeadsAnalysisTotal, LeadsAnalysisTotalType} from "@/api/leads.ts";
import * as echarts from 'echarts';
import { EChartsType } from 'echarts';
// import {useUserStore} from "@/stores/userStore.ts";
const phaseChart = ref<HTMLElement>();
const statusChart = ref<HTMLElement>();

// const store = useUserStore();
// const omniUserUuid = computed(() => store.user?.omni_user_uuid as string);

const omniUserUuid = localStorage.getItem('omni_user_uuid') as string;

// 获取当前日期
const today = new Date();
const startMonthDate = format(startOfMonth(today), 'yyyy-MM-dd')
const endMonthDate = format(endOfMonth(today), 'yyyy-MM-dd')
const queryParam = ref<LeadsAnalysisDataType>({
  sale_uuid:omniUserUuid,
  start:startMonthDate,
  end:endMonthDate,
})
const selectDateType = ref("month")
const selectDateLabel = ref("本月")
const showDatePopup = ref(false);
const customDateRef = ref<InstanceType<typeof CustomDate> | null>(null);


const phaseEchartsInstance = ref<EChartsType>();
const statusEchartsInstance = ref<EChartsType>();
const keys: (keyof LeadsAnalysisTotalType)[] = [
  "saleNotFollow",
  "transferOut",
  "saleNew",
  "poolUnFollow",
  "poolNew",
  "recycle"
];
const analysis = ()=>{
  //总数
  try {
    LeadsAnalysisTotal(queryParam.value).then((response)=>{
      console.log(response.data)
      if (response.data) {
        // 仅循环指定的键
        for (const key of keys) {
          const num = response.data[key]; // 获取当前属性值
          const item = dataInfo.value.find(info => info.type === key);
          if (item) {
            item.num = num; // 更新对应的 dataInfo 中的 num 属性
          }
        }
      }
    })
  }catch (e){
    console.log(e)
  }

  //图标
  try {
    LeadsAnalysisChart(queryParam.value).then((response) => {
      if (response.data && statusChart.value && phaseChart.value) {
        if(phaseEchartsInstance.value){
          phaseEchartsInstance.value.dispose()
        }
        if(statusEchartsInstance.value){
          statusEchartsInstance.value.dispose()
        }

        //阶段
        phaseEchartsInstance.value = echarts.init(phaseChart.value);
        phaseBarOption.yAxis.data = response.data.phase.yAxisData;
        phaseBarOption.series[0].data = response.data.phase.seriesData;
        phaseEchartsInstance.value.setOption(phaseBarOption);


        phaseFunnelOption.legend.data = response.data.phaseFunnel.yAxisData;
        phaseFunnelOption.series[0].data = response.data.phaseFunnel.seriesData;


        //状态
        statusEchartsInstance.value = echarts.init(statusChart.value);
        statusBarOption.yAxis.data = response.data.status.yAxisData;
        statusBarOption.series[0].data = response.data.status.seriesData;
        statusEchartsInstance.value.setOption(statusBarOption);
      }
    })
  } catch (e) {
    console.log(e);
  } finally {

  }
}

const switchDate = ()=>{
  showDatePopup.value = true
}

const updateParentSelectDataType = (newValue: string,dateLabel:string) =>{
  selectDateType.value = newValue
  selectDateLabel.value = dateLabel
}
const cancelDate = ()=>{
  if (customDateRef.value && 'triggerCancel' in customDateRef.value) {
    (customDateRef.value as any).triggerCancel("month");
  }
  queryParam.value = {
    sale_uuid:omniUserUuid,
    start:startMonthDate,
    end:endMonthDate
  }

  selectDateType.value = 'month'
  selectDateLabel.value = '本月'
  showDatePopup.value = false
}
const confirmDate = ()=>{
  if (customDateRef.value && 'triggerConfirm' in customDateRef.value) {
    const dateRange = (customDateRef.value as any).triggerConfirm()
    if (dateRange){
      const {gte,lte} = dateRange
      queryParam.value = {
        sale_uuid:omniUserUuid,
        start:gte,
        end:lte
      }
    }
  }
  showDatePopup.value = false
}

const isEqual =(obj1: LeadsAnalysisDataType, obj2: LeadsAnalysisDataType): boolean =>{
  return obj1.start === obj2.start && obj1.end === obj2.end;
}
watch(queryParam, (newValue, oldValue) => {
  if(!isEqual(newValue,oldValue)){
    analysis()
  }
}, { deep: true });



const phaseChartType = ref("bar")
const switchStatusChartType=(type:string)=>{
  phaseChartType.value = type
  switchPhaseChart(type)
}


// 定义 dataInfo 的类型
interface DataItem {
  type: string
  name: string
  num: number
  info: string
}
const dataInfo = ref<DataItem[]>([
  {type:"saleNotFollow",name: "未跟进", num: 0, info: "截止所选时间段内最后一天所有未跟进的潜客数量（当前未跟进定义：没有更新过潜客状态或潜客备注）"},
  {type:"transferOut",name: "已转出", num: 0, info: "截止所选时间段内最后一天转出（即分配）给销售的潜客总数（所有的转出都算）"},
  {type:"saleNew",name: "新增潜客", num: 0, info: "所选时间段内分配给该成员的潜客总数量"},
  {type:"poolUnFollow",name: "公海池未认领", num: 0, info: "截止到所选时间段的最后一天各成员可见公海池潜客人数"},
  {type:"poolNew",name: "公海池新增", num: 0, info: "时间段内，公海池新增潜客总人数"},
  {type:"recycle",name: "被回收潜客", num: 0, info: "统计截止所选时间段内最后一天所有符合系统设置的回收规则而被回收的潜客数量"},
])


const selectInfo = ref<DataItem|null>(null);
const showInfoPopup = ref(false);
const showInfo = (item:DataItem)=>{
  showInfoPopup.value = true
  selectInfo.value = item
}

//1、状态配置
const statusBarOption = {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {},
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01]
  },
  yAxis: {
    type: 'category',
    //data: ['联系未应答', '已联系', '可后续', '已会面', '成单','丢单','培育','不合格','黑名单']
    data: [],
    inverse: true
  },
  series: [
    {
      //name: '2011',
      type: 'bar',
      data: [
        //{ value: 20, itemStyle: { color: '#3BA272' } },
      ],
      label: {
        show: true,
        position: 'right',
        formatter: '{c}'
      }
    }
  ]
}
//2、阶段配置
const phaseBarOption = {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {},
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01]
  },
  yAxis: {
    type: 'category',
    data: ['客户', '销售认可', '销售接受', '市场认可', '潜客'],
    inverse: true
  },
  series: [
    {
      //name: '2011',
      type: 'bar',
      data: [
        { value: 4, itemStyle: { color: '#5470C6' } },   // customer
        { value: 6, itemStyle: { color: '#FAC858' } }, // sql
        { value: 12, itemStyle: { color: '#EE6666' } }, // sal
        { value: 18, itemStyle: { color: '#73C0DE' } }, // mql
        { value: 20, itemStyle: { color: '#3BA272' } } // leads
      ],
      label: {
        show: true,
        position: 'right',
        formatter: '{c}'
      }
    }
  ]
}
const phaseFunnelOption = {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b} : {c}%'
  },
  toolbox: {
    feature: {
      //dataView: { readOnly: false },
      //restore: {},
      //saveAsImage: {}
    }
  },
  legend: {
    data: ['潜客', '市场认可', '销售接受', '销售认可', '客户'],
    inverse: true
  },
  series: [
    {
      name: 'Funnel',
      type: 'funnel',
      left: '10%',
      top: 60,
      bottom: 60,
      width: '80%',
      min: 0,
      max: 100,
      minSize: '0%',
      maxSize: '100%',
      sort: 'descending',
      gap: 2,
      label: {
        show: true,
        position: 'inside',
        textBorderColor: 'transparent', // 移除字体边框颜色
        textBorderWidth: 0, // 设置边框宽度为0
        formatter: '{c}%'
      },
      labelLine: {
        length: 10,
        lineStyle: {
          width: 1,
          type: 'solid'
        }
      },
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 1
      },
      emphasis: {
        label: {
          fontSize: 16
        }
      },
      data: [
        { value: 100, name: '潜客' },
        { value: 70, name: '市场认可' },
        { value: 40, name: '销售接受' },
        { value: 20, name: '销售认可' },
        { value: 5, name: '客户' }
      ]
    }
  ]
};

onMounted(() => {
  analysis()
});

const switchPhaseChart = (chartType:string) => {
  if (phaseEchartsInstance.value) {
    phaseEchartsInstance.value.dispose(); // 销毁原先的 ECharts 实例
  }

  phaseEchartsInstance.value = echarts.init(phaseChart.value);

  switch (chartType) {
    case 'bar':
      phaseEchartsInstance.value.setOption(phaseBarOption);
      break;
    case 'funnel':
      phaseEchartsInstance.value.setOption(phaseFunnelOption);
      break;
    default:
      return;
  }
};


</script>

<style scoped>
.infoDetail {
  color: #888;
  margin-top: 4px;
  font-size: 14px; /* 设置留资来源字体大小 */
}
</style>
